import { LanguageManager } from "./language/LanguageManager";
import { MoveStatus, PointXY } from "./Macro";
import RESSpriteFrame from "./RESSpriteFrame";
import Anim from "./utils/Anim";
import EffectUtils from "./utils/EffectUtils";
import GuideEffect from "./utils/GuideEffect";
import MoneyChange from "./utils/MoneyChange";
import NotifyEffect from "./utils/NotifyEffect";
import Utils from "./utils/Utils";


const { ccclass, property } = cc._decorator;

@ccclass
export default class GameUI extends cc.Component {
    @property(cc.Node)
    private finger: cc.Node = null
    @property(cc.Node)
    private contentNode: cc.Node = null
    @property(cc.Node)
    private drawNode: cc.Node = null
    @property(cc.Node)
    private maskBg: cc.Node = null
    @property(cc.Mask)
    private maskNode: cc.Mask = null
    @property(cc.PolygonCollider)
    private collider: cc.PolygonCollider = null
    @property(cc.Node)
    private nodeArr: cc.Node[] = [];
    @property(cc.Node)
    private pointArr: cc.Node[] = [];
    @property(cc.Node)
    private resultUI: cc.Node = null
    @property(cc.Label)
    private resultLb: cc.Label = null
    @property(cc.Node)
    private failUI: cc.Node = null
    @property(cc.Node)
    private guideNode: cc.Node = null
    @property(cc.Node)
    private successLight: cc.Node = null

    nowX: number = null
    nowY: number = null
    private allPointArr = []
    private tempPointArr = []  //保存已经过顶点的数组
    private _nodeArr: any = null
    private _pointArr: any = null
    private bgmAudioFlag: boolean = true
    private canPlayMusic: boolean = false
    private colliderPoints: any = null
    private clearWidth: number = 28
    graphics: any = null
    moveStatus: number = null
    judgeFlag: boolean = true  //是否需要判断交点，到达交点时关闭，离开交点后打开
    turnFlag: boolean = true
    currentPointIndex: number = -1  //当前顶点索引
    lastPointIndex: any = null
    needJudge: boolean = true  //（在交点范围内就不需要判断）
    showFailFlag:boolean = true

    onLoad() {
        cc.director.getPhysicsManager().enabled = true;
    }
    protected start(): void {
        PlayerAdSdk.init();
        cc.director.getPhysicsManager().enabled = true;
        this.resize()
        let that = this;
        /**屏幕旋转尺寸改变 */
        cc.view.setResizeCallback(() => {
            that.resize();
        })
        cc.find('Canvas').on('touchstart', () => {
            this.canPlayMusic = true
            this.bgmAudioFlag && cc.audioEngine.play(RESSpriteFrame.instance.bgmAudioClip, false, 1)
            this.bgmAudioFlag = false
        })
        this.guideNode.active = true
        this.resize()
        this.resultUI.scale = this.failUI.scale = 0
        this.maskBg.on(cc.Node.EventType.TOUCH_START, this.touchStartFunc, this)
        this.maskBg.on(cc.Node.EventType.TOUCH_END, this.touchEndFunc, this)
        this.colliderPoints = this.collider.points
        this.graphics = this.maskNode._graphics
        this._nodeArr = [...this.nodeArr]
        this._pointArr = [...this.pointArr]
        for (let i = 0; i < this.nodeArr.length; i++) {
            this.allPointArr.push(this.nodeArr[i])
        }
        this.allPointArr.push(this.nodeArr[0])
        this.allPointArr.push(this.nodeArr[1])
    }
    private touchStartFunc(e) {
        this.guideNode.active = false
        this.finger.active = true
        let pos = e.getLocation()
        let touchoPos = this.maskBg.parent.convertToNodeSpaceAR(cc.v3(pos.x, pos.y))
        let isInCollider = cc.Intersection.pointInPolygon(cc.v2(touchoPos.x, touchoPos.y), this.colliderPoints)
        console.log('isIN', isInCollider)
        if (isInCollider) {
            pos = this.finger.parent.convertToNodeSpaceAR(pos)
            this.finger.x = pos.x
            this.finger.y = pos.y
            this.nowX = touchoPos.x + this.collider.offset.x
            this.nowY = touchoPos.y + this.collider.offset.y
            this.maskBg.on(cc.Node.EventType.TOUCH_MOVE, this.touchMoveFunc, this)
            // this.judgePoint(pos)
        }
    }
    private getPos(e) {
        return this.maskBg.convertToNodeSpaceAR(e.getLocation())
    }
    private touchMoveFunc(e) {
        let touchPos = e.getLocation()
        touchPos = this.maskBg.parent.convertToNodeSpaceAR(cc.v3(touchPos.x, touchPos.y))
        if (touchPos.y < LimitMacro.RoundYXMin) {
            this.clearWidth = 50
        } else {
            this.clearWidth = 35
        }
        let isInCollider = cc.Intersection.pointInPolygon(cc.v2(touchPos.x + this.collider.offset.x, touchPos.y + this.collider.offset.y), this.colliderPoints)
        let pos = this.getPos(e)
        let delta = e.getDelta()
        let pos1 = e.getLocation()
        pos1 = this.finger.parent.convertToNodeSpaceAR(pos1)
        this.finger.setPosition(pos1)
        this.clearFunc(pos)
        if (this._nodeArr.length > 0) {
            this.judgePoint(pos)
        } else {
            this.scheduleOnce(this.showSuccessUI, 0.6)
        }
    }
    //成功弹窗
    private showSuccessUI() {
        console.log('结束aaaa', this._nodeArr);
        cc.audioEngine.play(RESSpriteFrame.instance.winAudioClip,false,2)
        NotifyEffect.NormalShowUI(this.resultUI, null, 0.1, false, 0, 1, 0, 0.2,(()=>{
            cc.audioEngine.play(RESSpriteFrame.instance.cherrUpAudioClip,false,1)
        }))
        this.maskBg.off(cc.Node.EventType.TOUCH_START, this.touchStartFunc, this)
        this.maskBg.off(cc.Node.EventType.TOUCH_MOVE, this.clearFunc, this)
        this.maskBg.off(cc.Node.EventType.TOUCH_END, this.touchEndFunc, this)
        this.graphics.clear()
        this.initData()
    }
    private showFailUI() {
        console.log('结束aaaa', this._nodeArr);
        this.graphics.clear()
        this.maskBg.off(cc.Node.EventType.TOUCH_START, this.touchStartFunc, this)
        this.maskBg.off(cc.Node.EventType.TOUCH_MOVE, this.clearFunc, this)
        this.maskBg.off(cc.Node.EventType.TOUCH_END, this.touchEndFunc, this)
        this.initData()
        setTimeout(() => {
            NotifyEffect.NormalShowUI(this.failUI, null, 0.1, false, 0, 1, 0, 0.4,(()=>{
                cc.audioEngine.play(RESSpriteFrame.instance.loseUpAudioClip,false,2)
            }))
            this.resultUI.active = true
            this.graphics.clear()
        }, 300);
    }
    private clearFunc(pos) {
        this.graphics.circle(pos.x + 16.742, pos.y - 23.193, this.clearWidth)   //maskNode的偏移量
        this.graphics.fill()
    }
    private getRandomInt(min: number, max: number) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }
    private touchEndFunc() {
        this.unschedule(this.showSuccessUI)
        if (this._nodeArr.length == 0) {
            this.resultLb.string = 'SUCCESS'
            this.showSuccessUI()
        } else {
            if(this.showFailFlag){
                this.showFailFlag = false
                this.showFailUI()
            }
        }
    }
    private initData() {  //初始化数据
        this._nodeArr = [...this.nodeArr]
        this.nowX = this.nowY = null
        this.moveStatus = null
        this.turnFlag = true
        this.judgeFlag = true
        this.allPointArr = []
        for (let i = 0; i < this.nodeArr.length; i++) {
            this.allPointArr.push(this.nodeArr[i])
        }
        this.allPointArr.push(this.nodeArr[0])
        this.allPointArr.push(this.nodeArr[0])
        this.allPointArr.push(this.nodeArr[1])
    }
    private judgePoint(pos) {  //判断经过的点
        for (let i = 0; i < this.nodeArr.length; i++) {
            let nodeAbox = this.nodeArr[i].getBoundingBoxToWorld()
            let fingerBox = this.finger.getBoundingBoxToWorld()
            let isIn = nodeAbox.intersects(fingerBox) 
            let isIn1 = Math.abs(this.nodeArr[i].x - pos.x) < LimitMacro.diffMax && Math.abs(this.nodeArr[i].y - pos.y) < LimitMacro.diffMax
            if (isIn1) {
                if (this.needJudge) {
                    this.currentPointIndex = i
                    this.needJudge = false
                    console.log(`到达交点${i}`);
                    //判断交点是否重复逻辑
                    let isRepaet = true
                    this.tempPointArr.push(this.nodeArr[i])
                    for (let i = 0; i < this.allPointArr.length; i++) {
                        if (this.allPointArr[i] == this.tempPointArr[0]) {
                            this.tempPointArr.splice(0, 1)
                            this.allPointArr.splice(i, 1)
                            isRepaet = false
                            break;
                        }
                    }
                    // let isRepaet = this.judgeRepeat(this.tempPointArr, this.allPointArr)
                    if (isRepaet) {
                        if(this.showFailFlag){
                            this.showFailFlag = false
                            this.showFailUI()
                        }
                        
                        console.log('交点重复111', this.allPointArr, this.tempPointArr);
                        return;
                    }
                    for (let j = 0; j < this._nodeArr.length; j++) {
                        if (this._nodeArr[j].name == this.nodeArr[i].name) {
                            this._nodeArr.splice(j, 1)
                            break;
                        }
                    }
                }
                break;
            }
            //不在交点范围  --- 重新打开needJudge进行判断
            if (i == this.nodeArr.length - 1 && !this.needJudge) {
                this.needJudge = true
                this.lastPointIndex = this.currentPointIndex
                this.currentPointIndex = -1
                console.log('在交点外');
            }
        }
        for (let i = 0; i < this._pointArr.length; i++) {  //经过其他的点
            if (Math.abs(this._pointArr[i].x - pos.x) < LimitMacro.diffMax && Math.abs(this._pointArr[i].y - pos.y) < LimitMacro.diffMax) {
                this._pointArr.splice(i, 1)
                // console.log('_pointArr', this._pointArr);
                break;
            }
        }
        if (this.lastPointIndex == this.currentPointIndex) {  //交点重复
            console.log('交点重复，游戏结束');
            if(this.showFailFlag){
                this.showFailFlag = false
                this.showFailUI()
            }
            return;
        }
    }
    //初始化范围
    private initLimit(pos, delta = null) {
        if (pos.y > LimitMacro.CenterYMin && pos.y < LimitMacro.CenterYMax) {  //顶点0的横边上
            this.nowY = PointXY.CenterY
        }
        if (pos.x > LimitMacro.CenterXMin && pos.x < LimitMacro.CenterXMax && pos.y > LimitMacro.CenterYMin) {  //顶点0上的竖边
            this.nowX = PointXY.CenterX
        }
        if (pos.y > LimitMacro.MiddleYMin && pos.y < LimitMacro.MiddleYMax) {  //顶点1上的横边
            this.nowY = PointXY.MiddleY
        }
        if (pos.y > LimitMacro.MiddleTopYMin && pos.y < LimitMacro.MiddleTopYMax) {  //顶点2上的横边
            this.nowY = PointXY.MiddleTopY
        }
        if (pos.x > LimitMacro.LeftBottomXMin && pos.x < LimitMacro.LeftBottomXMax && pos.y > LimitMacro.CenterYMin) {  //矩形坐下顶点4上的竖边
            this.nowX = PointXY.LeftBottomX
        }
        if (pos.x > LimitMacro.RoundLeftXMin && pos.x < LimitMacro.RoundLeftXMax && pos.y > LimitMacro.CenterYMin) {  //半圆左顶点顶点5
            this.nowX = PointXY.RoundLeftX
        }
        if (pos.x > LimitMacro.RoundRightXMin && pos.x < LimitMacro.RoundRightXMax && pos.y > LimitMacro.CenterYMin) {  //半圆右顶点顶点6
            this.nowX = PointXY.RoundRightX
        }
        if (this.nowY < LimitMacro.RoundYXMin) {
            this.clearWidth = 50
        } else {
            this.clearWidth = 30
        }

    }
    private resize() {
        const canvasValue: any = cc.Canvas.instance;
        let frameSize = cc.view.getFrameSize();
        let isVerTical = cc.winSize.height > cc.winSize.width
        if (isVerTical) {//竖屏
            if (cc.winSize.width / cc.winSize.height > 0.7) {
                cc.Canvas.instance.fitHeight = true;
                cc.Canvas.instance.fitWidth = false;
            } else {
                cc.Canvas.instance.fitHeight = false;
                cc.Canvas.instance.fitWidth = true;
            }
        } else {
            cc.Canvas.instance.fitHeight = true;
            cc.Canvas.instance.fitWidth = false;
        }
        cc.director.getScene().getComponentsInChildren(cc.Widget).forEach(function (t) {
            t.updateAlignment()
        });
    }
    private cashoutFunc() {
        console.log('跳转');
        this.canPlayMusic && cc.audioEngine.play(RESSpriteFrame.instance.clickAudioClip, false, 1)
        PlayerAdSdk.gameEnd()
        PlayerAdSdk.jumpStore()
    }
    protected onDisable(): void {
        // this.cashOutBtn.off(cc.Node.EventType.TOUCH_START,this.cashoutFunc,this)
    }
    private testFunc() {
        // console.log(11);
    }
}   
